import Vue from 'vue';
import VueRouter from 'vue-router';
import store from './store/index';
import routers from './routes/router';
import App from './App.vue';
import ElementUI, { Loading } from 'element-ui';
import moment from 'moment';
// import mock from './mock';
import './assets/css/reset.css';
import './assets/css/element-variables.css';
import 'element-ui/lib/theme-chalk/index.css';
import "./assets/icon/excel/iconfont.css"

/*全局加载axios拦截器---配置axios的原型链*/
import './axios/axios';
import requestApiError from './axios/plugin';
// import 'lib-flexible/flexible';

// 以下为bpmn工作流绘图工具的样式
import 'bpmn-js/dist/assets/diagram-js.css'; // 左边工具栏以及编辑节点的样式
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';
import '@bpmn/css/app.less';

import { isInMenuList, isInPermissinList } from './utils/permission';
// require('@/static/workbench/index.js');

// 初始化 window.uid
let search = window.location.href.split('?')[1] || '';
search = search.split('#')[0] || '';
const searchParams = new URLSearchParams(search);
window.uid = searchParams.get('uid') || '';
window.isRecord = searchParams.get('isRecord') || '1'; // 0|1 控制显示双录按钮

Vue.prototype.$moment = moment;

// @input="e => form.name = validForbid(e)"
Vue.prototype.validForbid = function (value) {
	value = value.replace(/[`~@$^&()=<>|\\[\]·~@￥%……&（）——=|《》【】]/g, '').replace(/\s/g, '');
	return value;
};

Vue.prototype.validWordsSpace = function (value) {
	value = value.replace(/\s/g, '');
	return value;
};

//限制input输入框,强制只能输入整数
Vue.prototype.validateCheckNum = function (value) {
	value = value.replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、A-Za-z\u4E00-\u9FA5]/g, '').replace(/\s/g, '');
	return value;
};

//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push;
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err);
};

Vue.prototype.$paramsValidate = function (params) {
	let flag = true;

	for (var key in params) {
		if (params[key] != '0' && !params[key]) {
			this.$message.error('请完整填写信息！');
			return false; // 终止程序
		}
	}

	return flag;
};
//限制input输入框输入特殊符号
Vue.prototype.validForbidFeatureSymbols = function (value) {
	value = value.replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g, '').replace(/\s/g, '');
	return value;
};

//el-input自动获取焦点
Vue.directive('focus', {
	inserted: function (el) {
		el.querySelector('input').focus();
	}
});

// 菜单权限控制
Vue.directive('menupermission', {
	bind: function (el, binding, vnode) {
		vnode.context.$nextTick(() => {
			const permission = binding.value; // 获取权限值
			let have_permissions = localStorage.getItem(`zco_route_permission_${window.uid}`) || '[]';
			have_permissions = JSON.parse(have_permissions);
			if (!have_permissions.includes(permission) && el.parentElement) {
				// console.warn('menupermission ', have_permissions, permission);
				el.parentElement.removeChild(el); //不拥有该权限移除dom元素
			}
		});
	}
});
// 省略文件名
Vue.filter('flieOmit', (string, start = 2, end = -1) => {
	if (!string) return '';
	console.log(string.length);
	if (string.length <= 14) {
		return string;
	}
	if (string.includes('.')) {
		const [name, suffix] = string.split('.');
		console.log(name, suffix);
		if (name.length > 3) {
			const ago = name.slice(0, start);
			const later = name.slice(end);
			const res = `${ago}...${later}.${suffix}`;
			console.log(ago, later, res);
			return res;
		} else {
			const res = `${name}.${suffix}`;
			return res;
		}
	} else {
		const name = string;
		console.log(name);
		if (name.length > 3) {
			const ago = name.slice(0, start);
			const later = name.slice(end);
			const res = `${ago}...${later}`;
			return res;
		} else {
			const res = `${name}`;
			return res;
		}
	}
});

Vue.use(requestApiError);
Vue.use(ElementUI);
Vue.use(VueRouter);
// 替换原iview中的Spin
Vue.prototype.$Spin = {
	instance: null,
	show() {
		this.instance = Loading.service({ fullscreen: true });
	},
	hide() {
		if (this.instance) {
			this.instance.close();
			this.instance = null; // 可选：清理实例
		}
	}
};

let router = new VueRouter({
	base: '/',
	mode: 'hash',
	routes: routers
});

// 登录鉴权
router.beforeEach((to, from, next) => {
	// path: "/index/role/management" "/index/group"
	// to.path 在菜单列表之内，但不在用户权限之内，to 404
	if (isInMenuList(to.path) && !isInPermissinList(to.path)) {
		console.warn('beforeEach ', to.path);
		next('*');
	}

	if (to.path === '/login' || to.path === '/super' || to.path === '/superadmin' || to.path === '/accountLogin') {
		next();
	} else {
		let token = localStorage.getItem(`zco_admin_token_${window.uid}`);
		if (token === null || token === '') {
			next('/login');
		} else {
			const hasQuery = to.query.uid !== undefined;
			if (!hasQuery && to.path !== '/workbench') {
				// 如果路由中没有uid参数，添加它
				to.query.uid = window.uid || '';
				next({ path: to.path, query: to.query });
			} else {
				next();
			}
		}
	}
});



//取消 Vue 所有的日志与警告
Vue.config.silent = true;
new Vue({
	store,
	router,
	render: h => h(App)
}).$mount('#app');
